<?php
/**
 * Description: 员工相关
 * User: wuhao
 * Date: 2017-06-19
 * Time: 15:29
 */
namespace app\backend\controller;
use app\backend\controller\traits\AuthManager;
use app\backend\model\Building;
use app\backend\model\Member;
use Business\Business;
use think\Controller;
use think\Exception;

class EmployeeController extends Controller
{
    use AuthManager;
    private $_memberId = null;
    private $_dtype = null;
    private $_pdtype = null;
    private $_pmid = null;
    private $_allAuth = [];

    public function __construct()
    {
        parent::__construct();
        $memberInfo      = $this->getLoginInfo();
        $this->_memberId = $memberInfo['mid'];
        $this->_dtype    = $memberInfo['dtype'];
        $this->_pdtype   = $memberInfo['p_dtype'];
        $this->_pmid     = $memberInfo['p_mid'];
        $this->_allAuth  = $this->getPower($this->_memberId, $this->_dtype);
    }

    /**
     * @comment 新建员工
     * @author wuhao
     * @return json
     */
    public function createEmployee()
    {
        $code = 200; $msg = '';
        try {
            $name     = I('post.name', '', 'strval');//姓名
            $mobile   = I('post.mobile', '', 'strval');//手机号
            $status   = I('post.status', 0, 'intval');//启用状态 0=未启用 1=启用
            $password = I('post.password', '', 'strval');//密码
            if (!$name || !$mobile || !ismobile($mobile) || !in_array($status, [0,1]) || !$password) {
                throw new Exception('参数有误', 400);
            }
            $memberModel = new Member();
            //检验手机号
            if ($memberModel->getMemberInfo(['mobile' => $mobile], 'id')) {
                throw new Exception('手机号已经注册过了', 400);
            }
            //检验密码
            $res = chkPassword1($password);
            if ($res !== true) {
                throw new Exception($res, 400);
            }
            //生成登录账号
            $business = new Business();
            $account  = $business->_generateAccount(7);

            //获取父账号房源权限
            $buildModel = new Building();
            $houseList = $buildModel->getOwnerHouse($this->_memberId, $this->_dtype);
            $houseAuth = [];
            if ($houseList) {
                $houseAuth = array_column($houseList, 'id');
            }

            $data   = [
                'dtype'        => 7,
                'username'     => $account,
                'mobile'       => $mobile,
                'password'     => md5(md5($password)),
                'withdraw_pwd' => '',
                'status'       => $status,
                'nickname'     => $name,
                'id_card'      => '',
                'license'      => '',
                'user_type'    => 0,
                'member_auth'  => json_encode($this->_allAuth),
                'house_auth'   => json_encode($houseAuth),
                'update_time'  => time(),
                'create_time'  => time(),
            ];
            $id = $memberModel->addMember($data);
            if (!$id) {
                zft_log('add_employee', $memberModel->getLastSql());
                throw new Exception('添加失败', 400);
            }

            //新增余额
            $tmp = [
                'mid'   => $id,
                'money' => 0,
            ];
            $resAddMoney = $memberModel->addMemberMoney($tmp);
            if (!$resAddMoney) {
                zft_log('add_money_fail', json_encode($tmp));
            }

            //新增关联关系
            $value = ['parent_id' => $this->_memberId, 'son_id' => $id, 'son_id_type' => 1, 'ctime' => time()];
            $res = $memberModel->addRelation($value);
            if (!$res) {
                zft_log('add_relation', json_encode($res));
                throw new Exception('添加关联关系失败', 400);
            }


        } catch (Exception $e) {
            $code = $e->getCode();
            $msg  = $e->getMessage();
        }

        $this->apiReturn($code, [], $msg);
    }

    /**
     * @comment 获取员工列表
     * @author wuhao
     */
    public function getEmployee()
    {
        $code = 200; $msg = ''; $res = [];
        try {
            $query    = I('post.query', '', 'strval');  //昵称或手机号
            $page     = I('post.page', 1, 'intval');  //页数
            $pageSize = I('post.page_size', 15, 'intval');  //每页个数
            if (!is_numeric($page) || $page <=0 || !is_numeric($pageSize) || $pageSize <=0) {
                throw new Exception('参数有误', 400);
            }

            $memberModel = new Member();
            $res = $memberModel->getEmployee($this->_memberId, $query, $page, $pageSize);
            if (!$res) {
                throw new Exception('暂无数据', 400);
            }

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg  = $e->getMessage();
        }
        $this->apiReturn($code, $res, $msg);
    }

    /**
     * @comment 获取员工的房源权限
     * @author wuhao
     */
    public function getHouseAuth()
    {
        $code = 200; $msg = ''; $res = [];
        try {
            $id = I('post.id', '', 'intval');   //用户id
            if (!$id) {
                throw new Exception('id有误', 400);
            }
            $memberModel = new Member();
            $parentId = $memberModel->getParentId($id);
            if (!$parentId || $parentId['parent_id'] != $this->_memberId) {
                throw new Exception('不是自己的员工', 400);
            }

            $buildModel = new Building();
            //获取自己的所管理的房源列表
            $allHouse  = $buildModel->getOwnerHouse($this->_memberId, $this->_dtype);

            //获取员工房源数据
            $houseList = $buildModel->getOwnerHouse($id, 7);

            $buildArr  = array_unique(array_column($allHouse, 'building_id'));
            //获取对应的楼宇数据
            $buildList = $buildModel->getBuildingList(['id' => ['in', $buildArr]], 'id, name');
            $authArr = array_column($houseList, 'id');
            $res = [
                'all'   => $allHouse,
                'house' => $authArr,
                'build' => $buildList,
            ];

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg  = $e->getMessage();
        }

        $this->apiReturn($code, $res, $msg);
    }

    /**
     * @comment 获取员工菜单权限
     * @author wuhao
     */
    public function getMemberAuth()
    {
        $code = 200; $msg = ''; $res = [];
        try {
            $id = I('post.id', '', 'intval');   //用户id
            if (!$id) {
                throw new Exception('id有误', 400);
            }
            $memberModel = new Member();
            $parentId = $memberModel->getParentId($id);
            if (!$parentId || $parentId['parent_id'] != $this->_memberId) {
                throw new Exception('不是自己的员工', 400);
            }

            //获取权限
            $auth = $memberModel->getMemberInfoById($id, 'member_auth');

            $res = json_decode($auth['member_auth'], true);
            if (!$res) {
                throw new Exception('暂无数据', 400);
            }
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg  = $e->getMessage();
        }

        $this->apiReturn($code, $res, $msg);
    }

    /**
     * @comment 更新员工菜单权限
     * @author wuhao
     */
    public function updateMemberAuth()
    {
        $code = 200; $msg = ''; $res = [];
        try {
            $id   = I('post.id', '', 'intval');   //用户id
            $auth = I('post.auth');               //权限数组
            $auth = json_decode($auth, 'true');
            if (!$id || !is_array($auth)) {
                throw new Exception('参数有误', 400);
            }
            $memberModel = new Member();

            //判断是否是自己的员工
            $parentId = $memberModel->getParentId($id);
            if (!$parentId || $parentId['parent_id'] != $this->_memberId) {
                throw new Exception('不是自己的员工', 400);
            }

            //判断权限是否在父账号的权限范围内
            if ($auth) {
                foreach ($auth as $key =>  $v) {
                    if (!in_array($v, $this->_allAuth)) {
                        throw new Exception('设置的权限不能大于父账号权限', 400);
                    }
                    $auth[$key] = intval($v);
                }
            }

            //更新权限
            $result = $memberModel->updateUser($id, ['member_auth' => json_encode($auth)]);
            if (!$result) {
                zft_log('member_auth', $memberModel->getLastSql());
                throw new Exception('更新权限失败', 400);
            }
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg  = $e->getMessage();
        }

        $this->apiReturn($code, $res, $msg);
    }

    /**
     * @comment  更新房源权限
     * @author wuhao
     */
    public function updateHouseAuth()
    {
        $code = 200; $msg = ''; $res = [];
        try {
            $id   = I('post.id', '', 'intval');   //用户id
            $auth = I('post.auth');               //房源编号权限数组
            $auth = json_decode($auth, 'true');
            if (!$id || !is_array($auth)) {
                throw new Exception('参数有误', 400);
            }
            $memberModel = new Member();

            //判断是否是自己的员工
            $parentId = $memberModel->getParentId($id);
            if (!$parentId || $parentId['parent_id'] != $this->_memberId) {
                throw new Exception('不是自己的员工', 400);
            }

            //获取父账号房源权限
            $buildModel = new Building();
            $houseList  = $buildModel->getOwnerHouse($this->_memberId, $this->_dtype);
            $houseId = array_column($houseList, 'id');

            //判断权限是否在父账号的权限范围内
            if ($auth) {
                //获取对应的id
                foreach ($auth as $key =>  $v) {
                    if (!in_array($v, $houseId)) {
                        throw new Exception('设置的权限不能大于父账号权限', 400);
                    }
                    $auth[$key] = intval($v);
                }
            }

            //更新权限
            $result = $memberModel->updateUser($id, ['house_auth' => json_encode($auth)]);
            if (!$result) {
                zft_log('member_auth', $memberModel->getLastSql());
                throw new Exception('更新权限失败', 400);
            }
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg  = $e->getMessage();
        }

        $this->apiReturn($code, $res, $msg);
    }

    /**
     * @comment  更新员工启用状态
     * @author wuhao
     */
    public function updateStatus()
    {
        $code = 200; $msg = ''; $res = [];
        try {
            $id   = I('post.id', '', 'intval');   //用户id
            $status = I('post.status', 0, 'intval');     //0=禁用 1=启用
            if (!$id || !in_array($status, [0,1])) {
                throw new Exception('参数有误', 400);
            }
            $memberModel = new Member();

            //判断是否是自己的员工
            $parentId = $memberModel->getParentId($id);
            if (!$parentId || $parentId['parent_id'] != $this->_memberId) {
                throw new Exception('不是自己的员工', 400);
            }

            //更新员工状态
            $update = $memberModel->updateUser($id, ['status' => $status]);
            if (!$update) {
                zft_log('member_update', $memberModel->getLastSql());
                throw new Exception('更新失败', 400);
            }
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg  = $e->getMessage();
        }

        $this->apiReturn($code, $res, $msg);
    }

}

